<template>
  <!-- 生产单元管理 -->
  <div class="prodPlantManager">
    <basic-container>

      <!-- 表格内容 -->
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template  slot-scope="scope" slot="zdjg" >
          <el-form label-width="0px">
            <el-badge :value="(dataCAm[scope.row.id]==null?0:dataCAm[scope.row.id])" class="item">
              <el-button type="warning" size="small"  @click="handleCamera(scope.row.id)">绑定摄像头</el-button>
            </el-badge>
            <span v-if="cameraTagsErr" class="risk_error">请选择摄像头</span>
            <div class="point_list">
              <el-tag
                :key="index"
                v-for="(tag, index) in cameraTags"
                closable
                :disable-transitions="false"
                @close="closeCameraTag(index)">
                {{tag.fxdbh}}
              </el-tag>
            </div>
          </el-form>
        </template>
        <template slot-scope="scope" slot="ckxjjl">
            <el-button type="primary" size="small"  @click="handleSiteRecord">查看巡检记录</el-button>
        </template>
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.prod_unit_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button type="success"
                     size="small"
                     plain
                     v-if="permission.prod_unit_import"
                     icon="el-icon-upload2"
                     @click="handleImport">导入
          </el-button>
          <el-button type="warning"
                     size="small"
                     plain
                     v-if="permission.prod_unit_export"
                     icon="el-icon-download"
                     @click="handleExport">导出
          </el-button>
        </template>

        <!-- 现场图片表单自定义 -->
        <template slot="xczpForm">
          <div v-if="dialogType !== 'view'">
            <el-button
              size="small"
              type="primary"
              @click="uploadXCZP">
              上传图片
            </el-button>
            <span style="margin-left: 10px; color: #606266; font-size: 12px;">只能上传图片，最多选择3张</span>
            <input
              accept="image/*"
              ref="xczpUpload"
              id="xczpUpload"
              style="display: none;"
              type="file"
              @change="xczpUpload"
              multiple />
          </div>
        </template>

        <!-- 现场照片内容表单自定义 -->
        <template slot="xczpContentForm">
          <div class="xczp_content">
            <el-tag
              v-for="(item, index) in xczpFileList"
              :key="index"
              type="info"
              :closable="dialogType !== 'view'"
              @close="handleRemoveXCZP(index)"
            >
              <img
                :src="item.response.data.fileUrl"
                @click="previewXCZP(item)"
                alt />
            </el-tag>
          </div>
        </template>

        <template slot="mapForm">
          <div v-if="showMap">
            <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
              <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
                <template slot="append">
                  <el-button icon="el-icon-search" id="citySearch"></el-button>
                </template>
              </el-input>

              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <bm-marker :position="mapPosition" :dragging="true"></bm-marker>
            </baidu-map>
          </div>
        </template>
        <!-- 现场照片表格自定义 -->
        <template slot="xczp" slot-scope="scope">
          <div class="ope_row_div">
            <span v-if="scope.row['xczp'] === '' || scope.row['bladeFiles'].length === 0">-</span>
            <el-button v-else type="text" @click="handleViewPhoto(scope.row)">查看</el-button>
          </div>
        </template>
      </avue-crud>



      <el-dialog title="生产装置区域数据导入"
                 append-to-body
                 :visible.sync="excelBox"

                 width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false"
                   :upload-before="beforeUpload"
                   :upload-after="uploadAfter"
                   :upload-error="uploadError"
        >
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
      <!--      绑定摄像头表格-->

      <el-dialog title="选择 摄像头" :visible.sync="dialogCamera" append-to-body @close='closeDialogCamera' width="1200px">
        <avue-crud :option="cameraOption"
                   :table-loading="cameraLoading"
                   :data="cameraData"
                   :page.sync="cameraPage"
                   ref="cameraBinding"
                   @search-change="cameraSearchChange"
                   @search-reset="cameraSearchReset"
                   @selection-change="cameraSelectionChange"
                   @current-change="cameraCurrentChange"
                   @size-change="cameraSizeChange">
          <template slot-scope="{disabled,size}" slot="sxtmcSearch">
            <el-input placeholder="请输入摄像头名称" :disabled="disabled" :size="size" style="width:200px" v-model="bdsxt.sxtmc"></el-input>
          </template>

        </avue-crud>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialogCamera">取 消</el-button>
          <el-button type="primary" @click="chooseCamera()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 弹窗：图片 -->
      <viewpicture
        :localPicBox="localPicBox"
        :localPictures="localPictures"
        @confirmViewPicture="confirmViewPicture"
        @handleClosePicBox="handleClosePicBox">
      </viewpicture>


    </basic-container>
  </div>
</template>

<script>
  import { remove, update, add, getProdPlant,num,bindingCamera,getZdwxymcLinkInfo,getPage,removePic,uploadFiles} from "@/api/mmhi/prod_plant";
  import {getCameraBinding,getCameraBindingList} from "@/api/mmhi/major_supe_hazard_chem";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";
  import viewpicture from './components/viewpicture.vue';

  export default {
    components:{
      viewpicture
    },
    data() {
      return {
        bdsxt: {},
        prodPlantId:"",
        dataCAm:{},
        //地图设置
        mapPosition: {
          lng: 121.4472540000,
          lat: 31.3236200000
        },
        center: {
          lng: 121.4472540000,
          lat: 31.3236200000
        },
        zoom: 10,
        dragging: false,
        showMap: true,
        searchWord: "",
        mainFaults: {},
        localPicUrl: "",
        localPicBox: false,
        //照片上传设置
        xczpFileList: [],
        dialogType:'',
        photoBox: false,
        //摄像头表格设置
        cameraBusinessId:"",
        dialogCamera: false,
        cameraQuery: {},
        cameraLoading: true,
        cameraPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        cameraSelectionList: [],
        cameraOption: {
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          menu: false,
          addBtn: false,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "摄像头名称",
              prop: "sxtmc",
              align: "center",
              searchLabelWidth:90,
              search: true,
              searchslot:true
            },
            {
              label: "摄像头ID",
              prop: "sxtid",
              align: "center"
            },
            {
              label: "安装位置",
              prop: "azwz",
              align: "center"
            },
            {
              label: "所属区域",
              prop: "ssqy",
              align: "center"
            }
          ]
        },
        cameraData: [],
        cameraTags: [],
        cameraTagsErr: false,
        selectCamera: {},
        //表格主体设置
        form: {},
        query: {},
        excelBox: false,
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/productionPlantManage/import-prodPlant"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },
        option: {
          height:'auto',
          refreshBtn: true,
          columnBtn: false,
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "装置名称",
              prop: "zzmc",
              hide: false,
              search: true,
              align: "center",
              maxlength:50,
              rules: [{
                required: true,
                message: "请输入装置名称",
                trigger: "blur"
              }]
            },
            {
              label: "装置位号",
              prop: "zzwh",
              hide: false,
              maxlength:7,
              align: "center",
              rules: [{
                required: true,
                message: "请输入装置位号",
                trigger: "click"
              }]
            },
            {
              label: "装置型号",
              prop: "zzxh",
              hide: false,
              maxlength:15,
              align: "center",
              rules: [{
                required: true,
                message: "请输入装置型号",
                trigger: "blur"
              }],
            },
            {
              label: "装置位置",
              prop: "zzwz",
              hide: false,
              maxlength:100,
              align: "center",
              rules: [{
                required: true,
                message: "请输入装置位置",
                trigger: "blur"
              }],
            },
            {
              label: "是否关键装置",
              type: "select",
              align: "center",
              width: "100px",
              hide: false,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=deptInfo_yesno",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              prop: "sfgjzz",
              rules: [{
                required: true,
                message: "请选择场是否关键装置",
                trigger: "blur"
              }]

            },
            {
              label: '所属危险工艺',
              align: "center",
              prop: 'sswxgy',
              width: "100px",
              type:'select',
              hide: false,
              dicUrl: "/api/productionPlantManage/getZdwxgyList",
              props: {
                label: "dictValue",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择危险工艺",
                trigger: "blur"
              }]
            },
            {
              label: '涉及主要危化品',
              prop: 'sjzywhp',
              align: "center",
              width: "120px",
              maxlength:150,
              cascaderIndex:0,
              hide: false,
              dicFlag: false,
              rules: [{
                required: true,
                message: "请选择主要危化品",
                trigger: "blur"
              }]
            },
            {
              label: "所属重大危险源id",
              align: "center",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              prop: "sszdwxyId",
              hide: true,
            },
            {
              label: "所属重大危险源单元名称",
              align: "center",
              type:"select",
              width: "160px",
              span:12,
              dicUrl: "/api/productionPlantManage/getZdwxymcList",
              props: {
                value: "zdwxymc"
              },
              prop: "sszdwxydymc",
              hide: false,
            },
            {
              label: "所属重大危险源单元编号",
              align: "center",
              width: "160px",
              prop: "sszdwxydybh",
              span:12,
              disabled:true,
              hide: false,
            },
            {
              label: "现场图片",
              prop: "xczp",
              align: "center",
              slot: true,
              span: 24,
              width: 80,
              formslot:true,
            },
            {
              label: "",
              prop: "xczpContent",
              hide: true,
              span: 24,
              formslot: true
            },
            {
              label: '',
              align: "center",
              prop: 'map',
              span: 24,
              hide: true,
              formslot: true,
            },
            {
              label: "经度",
              align: "center",
              prop: "jd",
              span:12,
              width: 90,
              hide: false,
              rules: [{
                required: true,
                message: "请输入经度",
                trigger: "click"
              }]
            },
            {
              label: "纬度",
              prop: "wd",
              align: "center",
              span:12,
              width: 90,
              hide: false,
              rules: [{
                required: true,
                message: "请输入纬度",
                trigger: "click"
              }]
            },
            {
              label: '装置相邻的周围环境',
              prop: 'zwhj',
              cascaderIndex:0,
              align: "center",
              maxlength:50,
              dicFlag: false,
              hide:true,
              rules: [{
                required: true,
                message: "请输入装置相邻的周围环境",
                trigger: "blur"
              }]
            },
            {
              label: "装置功能",
              align: "center",
              prop: "zzgn",
              maxlength:50,
              hide: true,
              rules: [{
                required: true,
                message: "请输入装置功能",
                trigger: "blur"
              }]
            },

            {
              label: "重点监管",
              align: "center",
              prop: "zdjg",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              props: {
                value: "id"
              },
              width:120,
              slot: true,
            },
            {
              label: "操作",
              align: "center",
              prop: "ckxjjl",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              width:125,
              slot: true,
            },
            {
              label: "自动化控制方式",
              align: "center",
              prop: "zdhkzfs",
              maxlength:50,
              hide: true,
              rules: [{
                required: false,
                message: "请输入自动化控制方式",
                trigger: "blur"
              }]
            },
            {
              label: "投用日期",
              align: "center",
              prop: "tyrq",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              hide: true,
              rules: [{
                required: true,
                message: "请输入投用日期",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:1000,
              span: 24,
              minRows: 6,
              hide: true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            }

          ]
        },
        data: [],
        localPictures: [],
        dataCameraBindingList:[]
      };
    },

    computed: {
      ...mapGetters(["permission"]),

      // 表格按钮权限
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.prod_plant_add, false),
          viewBtn: this.vaildData(this.permission.prod_plant_view, false),
          delBtn: this.vaildData(this.permission.prod_plant_delete, false),
          editBtn: this.vaildData(this.permission.prod_plant_edit, false)
        };
      },
      // 勾选项id
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },

      //现场照片id
      picIds() {
        let picIds = [];
        this.selectionList.forEach(ele => {
          picIds.push(ele.xczp);
        });
        return picIds.join(",");
      },

    },
    created() {
      this.getNum();
    },
    methods: {
      // 上传现场照片
      xczpUpload(element) {
        console.log(element);
        if(this.$refs.xczpUpload.files.length + this.xczpFileList.length > 3) {
          this.$message.warning("最多上传3张现场图片!");
          this.$refs.xczpUpload.value = null;
          return;
        }
        let formData = {};
        let files = this.$refs.xczpUpload.files;
        formData = new FormData();
        for(let i = 0 ; i < files.length ; i++) {
          formData.append("files", files[i]);
        }
        uploadFiles(formData).then(res => {
          if(!res.data.success) {
            return;
          }
          var resData = res.data.data;
          resData.forEach(item => {
            this.xczpFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: item
              }
            });
          });
          this.$refs.xczpUpload.value = null;
        });
      },
      // 点击上传图片按钮
      uploadXCZP() {
        document.getElementById("xczpUpload").click();
      },

      // 获取现场照片ids
      formatPictureIds(filelist) {
        var ids = [];
        filelist.forEach(item => {
          ids.push(item.response.data.id);
        });
        return ids.join(",");
      },

      // 删除现场照片
      handleRemoveXCZP(index) {
        this.xczpFileList.splice(index, 1);
      },

      // 上传现场图片前
      beforeUploadXCZP(file) {
        var isLt2M = file.size / 1024 / 1024 < 2;
        var isLimit = (this.xczpFileList.length + 1) <= 3 ;
        if (!isLt2M) {
          this.$message.warning('图片大小不能超过2MB!');
        }
        if (!isLimit) {
          this.$message.warning('最多上传3张现场图片!');
        }
        return isLt2M && isLimit;
      },

      // 上传现场图片成功
      uploadXCZPSuccess(response, file, fileList) {
        if(response.code !== 200 || response.success !== true) {
          return;
        }
        this.xczpFileList = [];
        fileList.forEach(item => {
          this.xczpFileList.push({
            name: item.name,
            response: {
              code: 200,
              data: Array.isArray(item.response.data) === true ? item.response.data[0] : item.response.data,
              msg: "操作成功",
              success: true
            }
          });
        });
      },
      // 查看现场照片
      handleViewPhoto(row) {
        this.localPictures = row.bladeFiles;
        this.localPicBox = true;
      },
      // 点击图片列表中已上传的现场图片
      previewXCZP(file) {
        if(file.response && file.response.code === 200 && file.response.data && file.response.data.fileUrl) {
          this.localPictures = [file.response.data];
          this.localPicBox = true;
        }
      },
      // 确认照片
      confirmViewPicture() {
        this.localPicBox = false;
      },
      // 关闭弹窗
      handleClosePicBox() {
        this.localPicBox = false;
      },

      // 地图处理事件
      handler({BMap, map}) {
        let _this = this;
        map.addEventListener('click', function(e) {
          _this.form.jd = e.point.lng
          _this.form.wd = e.point.lat
        });

        _this.$nextTick(() => {
          document.getElementById('citySearch').addEventListener('click', function() {
            let localSearch = new BMap.LocalSearch(map)
            localSearch.setSearchCompleteCallback(searchResult => {
              let poi = searchResult.getPoi(0)
              if(!poi) {
                return _this.$message.warning('该地址不存在')
              } else {
                _this.center = {
                  lng: poi.point.lng,
                  lat: poi.point.lat
                }
                _this.form.jd = poi.point.lng
                _this.form.wd = poi.point.lat
              }
            });
            localSearch.search(_this.searchWord);
          });
        })
      },

      // 导入前判断
      photobeforeUpload(file, done, loading) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'jpg'
        const extension2 = testmsg === 'png'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .jpg,.png 标准格式文件!');
          loading()
        } else {
          done()
        }
      },
      // 导入失败后
      photouploadError(error, column) {
        console.log(error,column);
        this.isFailed = true;
      },
      // 导入成功后
      photouploadAfter(res, done) {
        done();
        if(this.isFailed === true) {
          return;
        }
        this.photoBox = false;
        this.$message.success("上传成功");
        this.cancle();
      },
      //照片打开
      photoImg() {
        this.photoBox = true;
      },

      //摄像头整体方法开始
      // 打开绑定摄像头弹窗
      handleCamera(prodplantId) {
        this.bdsxt={}
        this.cameraBusinessId=prodplantId
        this.dialogCamera = true;
        getCameraBindingList(prodplantId, 1).then((data) => {
          this.dataCameraBindingList=data.data.data
        });
        this.cameraOnLoad(this.cameraPage);
      },

      // 关闭绑定摄像头弹窗
      closeDialogCamera() {
        this.cameraPage.currentPage = 1;
        this.dialogCamera = false;
      },

      // 摄像头获取表格数据
      cameraOnLoad(page, params = {}) {
        this.cameraLoading = true;
        getCameraBinding(page.currentPage, page.pageSize, Object.assign(params, this.bdsxt)).then(res => {
          const data = res.data.data;
          this.cameraPage.total = data.total;
          this.cameraData = data.records;
          this.cameraLoading = false;
          this.$nextTick(() => {
            this.cameraData.forEach(row => {

              this.dataCameraBindingList.forEach(item => {
                // alert(row+"   "+item)
                if(item.cameraId===row.id){
                  this.$refs.cameraBinding.toggleRowSelection(row, true);
                }
              })
            })
          })
        });
      },


      // 绑定摄像头清空勾选
      cameraSelectionClear() {
        this.cameraSelectionList = [];
        this.$refs.cameraBinding.toggleSelection();
      },

      // 摄像头搜索条件改变事件
      cameraSearchChange(params, done) {
        this.cameraQuery = params;
        this.cameraPage.currentPage = 1;
        this.cameraOnLoad(this.cameraPage, params);
        done();
      },
      // 摄像头清空搜索条件
      cameraSearchReset() {
        this.bdsxt={}
        this.cameraQuery = {};
        this.cameraOnLoad(this.cameraPage);
      },

      // 摄像头勾选
      cameraSelectionChange(list) {
        this.cameraSelectionList = list;
      },

      // 摄像头换页数
      cameraCurrentChange(currentPage){
        var pageSelectIds = [];
        var pageAllIds = [];
        this.cameraSelectionList.forEach(item => {
          this.selectCamera[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.cameraData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(var id in this.selectCamera) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCamera[id];
          }
        }
        this.cameraPage.currentPage = currentPage;
        this.cameraOnLoad(this.cameraPage);
        this.cameraSelectionList=[]
      },

      // 摄像头换每页显示数量
      cameraSizeChange(pageSize){
        this.cameraPage.pageSize = pageSize;
        this.riskOnLoad(this.cameraPage);
      },

      // 选择摄像头
      chooseCamera(done,loading) {
        var pageSelectIds = [];
        var pageAllIds = [];
        this.cameraSelectionList.forEach(item => {
          this.selectCamera[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.cameraData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectCamera) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCamera[id];
          }
        }
        if(this.selectCamera === undefined || JSON.stringify(this.selectCamera) === "{}") {
          this.$message.warning("请选择摄像头");
          return;
        }
        this.cameraTagsErr = false;

        var ids = pageSelectIds.join(",");
        var id = this.cameraBusinessId;
        bindingCamera(ids,id).then(() => {
          this.$message.success("绑定成功!");
          this.closeDialogCamera();
          this.onLoad(this.page);
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
        this.cameraBusinessId=""
        this.closeDialogCamera();
        this.cameraSearchReset()
      },

      // 删除某一个camera标签
      closeCameraTag(index) {
        this.cameraTags.splice(index, 1);
        if(this.cameraTags.length === 0) {
          this.cameraTagsErr = true;
        }
      },

      //获取绑定数
      getNum() {
        num().then((data) => {
          this.dataCAm=data.data.data
        }, error => {
          window.console.log(error);
        });
      },

      //摄像头整体方法结束

      // 新增
      rowSave(row, done, loading) {
        row.xczp=this.xczpFileList.length==0?"":this.formatPictureIds(this.xczpFileList)
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        }, error => {
          loading();
          window.console.log(error);
        });

      },

      // 编辑
      rowUpdate(row, index, done,loading) {

        row.xczp=this.xczpFileList.length==0?"":this.formatPictureIds(this.xczpFileList)
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

      // 删除一条
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (row.xczp!="") {
            removePic(row.xczp)
          }
          return remove(row.id);
        }).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
      },

      // 删除多条
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.picIds.split(",").forEach(picId=>{
            if (picId!=="") {
              removePic(picId);
            }
          })

          return remove(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
        this.pic=false
      },

      // 打开弹窗前
      beforeOpen(done, type) {
        switch(type) {
          case 'add':
            this.dialogType =''
            this.xczpFileList = [];
            this.showMap = true;
            this.mapPosition = {
              lng: 121.4472540000,
              lat: 31.3236200000
            };
            this.center = {
              lng: 121.4472540000,
              lat: 31.3236200000
            };
            done();
            break
          case 'edit':
            this.dialogType =''
            this.showMap = true;
            this.center = {
              lng: this.form.jd,
              lat: this.form.wd
            };
            this.zoom = 8;
            this.xczpFileList = [];
            this.form.bladeFiles.forEach(item => {
              this.xczpFileList.push({
                name: item.fileName,
                response: {
                  code: 200,
                  data: item,
                  msg: "操作成功",
                  success: true
                }
              });
            });
            getProdPlant(this.form.id).then(res => {
              this.form = res.data.data;
            });
            done();
            break
          case 'view':
            this.xczpFileList = [];
            this.form.bladeFiles.forEach(item => {
              this.xczpFileList.push({
                name: item.fileName,
                response: {
                  code: 200,
                  data: item,
                  msg: "操作成功",
                  success: true
                }
              });
            });
            this.showMap = false;
            this.dialogType = type;
            done();
            break
          default:
            break
        }

      },
      // 清空搜索条件
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },

      // 搜索条件改变事件
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },

      // 勾选
      selectionChange(list) {
        this.selectionList = list;
      },

      // 清空勾选
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },

      // 换页数
      currentChange(currentPage){
        this.page.currentPage = currentPage;
        this.onLoad(this.page);
      },

      // 换每页显示数量
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
        this.onLoad(this.page);
      },

      // 刷新
      refreshChange() {
        this.onLoad(this.page, this.query);
      },

      // 获取表格数据
      onLoad(page, params = {}) {
        this.loading = true;
        getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
          this.getNum();
        });
      },

      //打开导入弹窗
      handleImport() {
        // this.excelForm={}
        this.excelBox = true;
      },

      // 导入前判断
      beforeUpload(file, done, loading) {
        this.uploadFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },
      // 导入成功后1
      uploadAfter1() {
        this.excelBox = false;
        this.$message.success("上传成功");
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      // 导入成功后
      uploadAfter(res, done) {
        done();
        if(this.uploadFailed === true) {
          return;
        }
        this.uploadAfter1()
      },
      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.uploadFailed = true;
      },

      //导出摸板
      handleTemplate() {
        window.open(`/api/productionPlantManage/export-template?${this.website.tokenHeader}=${getToken()}`);
      },

      //导出生产装置
      handleExport() {
        this.$confirm("是否导出生产装置信息数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let zzmc = this.query.zzmc !== undefined && this.query.zzmc !== "" && this.query.zzmc !== null ? this.query.zzmc : "";
          window.open(`/api/productionPlantManage/export-prodPlant?${this.website.tokenHeader}=${getToken()}&zzmc=${zzmc}`);
        });
      },
    },
    watch: {
      //重大危险源联动
      'form.sszdwxydymc':{// form是表单或者表格绑定的数据集，v-model='form'
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getZdwxymcLinkInfo(val).then(res=>{// 可以请求后端的方法
              this.form.sszdwxyId= res.data.data[0].id;
              this.form.sszdwxydybh = res.data.data[0].zdwxybh;
            });
          }
        },
        immediate: true
      },

      // 表单经度
      'form.jd' (val) {
        if(val) {
          this.mapPosition.lng = val / 1
        }
      },

      // 表单纬度
      'form.wd' (val) {
        if(val) {
          this.mapPosition.lat = val / 1
        }
      },
      //给表单的租户id赋值
      'form.tenantId'() {
        if (this.form.tenantId !== '' && this.initFlag) {
          this.initData(this.form.tenantId);
        }
      }
    }
  };
</script>
<style lang="scss">
  .prodPlantManager {
    .el-form-item__label {
      width: 86px !important;
    }

    .avue-form__row {
      .el-form-item__content {
        margin-left: 86px !important;
      }
    }
  }
  .riskpoint {
    .el-form-item__label {
      width: 86px !important;
    }

    .avue-form__row {
      .el-form-item__content {
        margin-left: 86px !important;
      }
    }

    .avue-crud__menu {
      .avue-crud__left {
        .el-radio {
          margin-left: 10px;
          margin-right: 10px;
        }
      }
    }
  }

  .anchorBL {
    display: none;
  }

  .siteinfo {
    .el-card__body {
      height: calc(100% - 35px);

      .avue-crud {
        height: calc(100% - 105px);
      }
    }
  }
</style>

<style lang="scss" scpoed>
  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 170px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 170px !important;
        }
      }
    }
  }

  .el-dialog__wrapper {
    .el-dialog__body {
      padding: 10px 20px 20px 20px;

      .el-form-item__label {
        width: 72px;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 72px;
        }
      }

      .avue-crud__menu {
        display: none;
      }
    }
  }
  .item {
    margin-top: 10px;
    margin-right: 40px;
    right: 3px;
  }
  .map {
    width: 100%;
    height: 500px;
  }
  .el-image {
    width: 100%;
    height: 100%;
  }
  .box {
    height: 100%;
  }
  .el-carousel {
    .el-carousel__container {
      height: 500px;
      text-align: center;

      img {
        height: 100%;
      }
    }
  }
  .jsbz_content,
  .xczp_content {
    width: 100%;
    height: 118px;
    line-height: 105px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;

    .el-tag {
      height: 100px;
      line-height: 100px;
      padding: 0px 10px 0px 0px;
      margin-left: 10px;
      margin-top: 10px;

      .el-icon-close {
        top: -84px;
      }
    }

    img {
      width: 98px;
      height: 98px;
      cursor: pointer;
    }
  }
</style>
